from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from apps.goods.models import SKU, GoodsCategory, SPUSpecification
from apps.meiduo_admin.utils import NumPage
from apps.meiduo_admin.serialziers.skus import SKUSerializer, SPUSpecificationSerializer


class SKUSViews(ModelViewSet):
    # 指定查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定权限
    permission_classes = [IsAdminUser]
    # 指定分页
    pagination_class = NumPage

    # 重写获取数据方法，根据不同数据获取不同的内容
    def get_queryset(self):
        # 获取keyword关键字
        key_world = self.request.query_params.get('keyword')
        # 根据关键字返回不同数据内容
        if key_world == '' or key_world == None:
            return self.queryset
        else:
            return SKU.objects.filter(name__contains=key_world)

    # 获取三级分分类
    @action(methods=['get'], detail=False)
    def categories(self, request):
        # 查询所有三级分类  下一级查询上一级 副表查询主表parent
        # 上一级查询下一级 主表查询副表 related_name='subs' 如果下一级为空说明当前数据是三级分类
        categories = GoodsCategory.objects.filter(subs=None)
        # 返回三级分离
        categorie_list = []
        for categorie in categories:
            categorie_list.append({
                'id': categorie.id,
                'name': categorie.name
            })

        return Response(categorie_list)

    # 获取spu商品的规格及规格选项
    def specs(self, request, pk):
        """

        :param request:
        :param pk:  spu商品id
        :return:
        """
        # 1、spu规格表
        spu_specs = SPUSpecification.objects.filter(spu_id=pk)
        # 2、序列化返回
        ser = SPUSpecificationSerializer(spu_specs, many=True)

        return Response(ser.data)

    # def retrieve(self, request, *args, **kwargs):
    #     pk = kwargs['pk']
    #     instance = self.get_object()
    #     # instance = SKU.objects.get(id=pk)
    #     serializer = self.get_serializer(instance)
    #     return Response(serializer.data)
